<?
function unsgzu($data) {
	$sX = gzuncompress($data);
	if ($sX===false) return array();
	$aX = unserialize($sX);
	if ($aX===false) return array();
	return $aX;
}
function gzcser($array) {
	return gzcompress(serialize($array));
}
function asgzcser($array) {
	return addslashes(gzcser($array));
}
function asgzc($data) {
	return addslashes(gzcompress($data));
}
function gzc($data) {
	return gzcompress($data);
}
function gzunc($data) {
	return gzuncompress($data);
}

function getUteDes($idUt) {
	global $objDB, $objSess;
	$sSql = "SELECT u.* FROM rgl_utenti u WHERE u.id_utente = ".intval($idUt);
	$objDB->query($sSql,'wfmModSta');
	if (!$aRec = $objDB->fetch('wfmModSta')) {
		return "?";
	}
	return $aRec['cod_utente']." - ".$aRec['cognome']." ".$aRec['nome'];
}
// funzioni varie
function _t($x,$p1='',$p2='',$p3='',$p4='',$p5='',$p6='') {
	global $aTraduzioni, $objDB, $objSess;
	if (RGL_REGISTRA_TESTI === true) {
		if (!is_object($objDB)) {
			$objDB = new rglDb();
		}
		$sSql = "REPLACE rgl_testi SET md5x = '". md5($x)
			."', testo_it = '".addslashes($x)."', time_rec=NOW()";
		$objDB->exec($sSql);
	}
	//dbg_($x.":".$objSess->lingua);
	if (is_null($aTraduzioni)) {
		if (!is_object($objSess)) {
			$objSess = new rglSession();
			if (defined("RGL_LINGUA_DEFAULT")) {
				$objSess->lingua = RGL_LINGUA_DEFAULT;
			} else {
				$objSess->lingua = 'it';
			}
		}
		if ($objSess->lingua == 'it' 
		|| !file_exists(RGL_TRADUZIONI_DIR."/testi_".$objSess->lingua.".txt")) {
			$aTraduzioni = "no-trad";
		} else {
			$aTraduzioni = array();
			if ($fh=fopen(RGL_TRADUZIONI_DIR."/testi_".$objSess->lingua.".txt",'rb')) {
				while($sRec = rtrim(fgets($fh,1024))) {
					$aX = explode("#@",$sRec);
					if (trim(rglVx($aX,1))=="") continue;
					$kX = md5($aX[0]);
					$aTraduzioni[$kX] = $aX[1];
				}
				fclose($fh);
			}
		}
		//dbg_($aTraduzioni);
	}
	
	if (is_array($aTraduzioni)) {
		$md5X = md5($x);
		//dbg_($x.":".$md5X);
		if (isset($aTraduzioni[$md5X])) {
			//dbg_("t_:".$x."=".$aTraduzioni[$md5X]);
			return sprintf($aTraduzioni[$md5X],$p1,$p2,$p3,$p4,$p5,$p6);
		}
	}
	return sprintf($x,$p1,$p2,$p3,$p4,$p5,$p6);
}

function headerDownLoad($lung, $fileName) {
	header("Pragma: public"); 
	header("Expires: 0"); 
	header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
	header("Cache-Control: private",false); 
	header("Content-Type: application/".substr($fileName,-3)); 
	header("Content-Transfer-Encoding:  binary"); 
	header('Content-Length: '.$lung);
	header('Content-disposition: attachment; filename="'.$fileName.'"');
}

/**
 * restituisce il valore dell'elemento $aX[$k0][$k1][$k2]...[$k9] o '' se non esiste tale elemento
 * ($k1 ... $k9 sono facoltativi - es. rglVx($aProva,'zxcv',2,'asdf') restituisce $aProva['zxcv'][2]['asdfd'])
 */
function rglVx($aX, $k0, $k1='',$k2='',$k3='',$k4='',$k5='',$k6='',$k7='',$k8='',$k9='',$k10=''
	,$k11='',$k12='',$k13='',$k14='',$k15='',$k16='',$k17='',$k18='',$k19='',$k20='') {
	if (!isset($aX[$k0])) {
		return '';
	}
	if ($k1==='') {
		return $aX[$k0];
	}
	if (!is_array($aX[$k0])) {
		return '';
	}
	return rglVx($aX[$k0],$k1,$k2,$k3,$k4,$k5,$k6,$k7,$k8,$k9,$k10
		,$k11,$k12,$k13,$k14,$k15,$k16,$k17,$k18,$k19,$k20);
}

function rglHeUtf8($x) {
	return htmlentities(utf8_encode($x));
}

function dbg_($mess) {
   global $objSess;
   if (defined('RGL_DBG_FLAG_DISPLAY')) {
		$flagDisplay = RGL_DBG_FLAG_DISPLAY;
	} else {
		$aDebugParam = unserialize(RGL_DEBUG_PARAM);
		$flagDisplay='N';
		if (is_array($aDebugParam)) {
			if (isset($aDebugParam['users']['*'])) {$flagDisplay = $aDebugParam['users']['*'];}
			if (is_object($objSess) and isset($aDebugParam['users'][$objSess->login])) {
				$flagDisplay = $aDebugParam['users'][$objSess->login];
			}
			if (is_object($objSess) and $objSess->backDoor) {
				$flagDisplay = 'D';
			}
		}	
	}
   if ($flagDisplay=='D') { 
		$rc = rglScriviLog('lastdebug',$mess);
		$rc = rglScriviLog('debug',$mess);
	   return $rc; 
   }
   if ($flagDisplay=='F') { 
		$rc = rglScriviLog('debug',$mess);
	   return $rc; 
   }
   return false; 
}

function rglLogErr($mess) {
	return rglLogErrWarn('error',$mess);
}

function rglLogWarn($mess) {
	return rglLogErrWarn('warning',$mess);
}

function rglLogErrWarn($tipo,$mess) {
   global $objSess, $aDebugParam;
	$rc = rglScriviLog($tipo,$mess);
   $flagDisplay="F";
	if (is_object($objSess) and is_array($aDebugParam)) {
		if (isset($aDebugParam['users']['*']))
			$flagDisplay = $aDebugParam['users']['*'];
		if (isset($aDebugParam['users'][$objSess->login]))
			$flagDisplay = $aDebugParam['users'][$objSess->login];
	}	
   if ($flagDisplay=='D') { 
		$rc = rglScriviLog('last'.$tipo,$mess);
	   return $rc; 
   }
   return false; 
}

function rglScriviLog($tipo,$mess) {
	//scrittura messaggio nel debug
    global $objSess, $aDebugParam;
    $filePath = RGL_FS_LOG_DIR."/$tipo";
    if (rand(1,10)==10) {
	   	if ($dh=@opendir(RGL_FS_LOG_DIR)) {
	   		$ls = strlen($tipo);
	   		while($fn=readdir($dh)) {
	   			if (strlen($fn) != ($ls+14) or substr($fn,0,$ls)!=$tipo) continue;
	   			if (substr($fn,$ls) < date('YmdHis',time()-3600*24*7)) {
	   				@unlink(RGL_FS_LOG_DIR."/$fn");
	   			}
	   		}
	   	}
    }
    if (file_exists($filePath)) {
	   	if (filesize($filePath) > 1000000) {
	   		@copy($filePath,$filePath.date('YmdHis'));
	   		@unlink($filePath);
	   	}
    }
    $sIdUt = (is_object($objSess))? $objSess->idUtente: "*";
    @file_put_contents($filePath, date("Y-m-d H:i:s")." ".$sIdUt." - ".
   	str_replace("\n"," <br>",print_r($mess,1))."\r\n",FILE_APPEND);
    //@chmod($filePath,0664);
    return true;
}

function getVar($nome) {
   global $_GET;
   if (!isset($_GET[$nome])) return '';
   if (!get_magic_quotes_gpc()) return $_GET[$nome];
   if (!is_array($_GET[$nome])) return stripslashes($_GET[$nome]);
   $aX = array();
   foreach($_GET[$nome] as $vX) {
   	$aX[] = stripslashes($vX);
   }
   return $aX;
}
function postVar($nome) {
   global $_POST;
   if (!isset($_POST[$nome])) return '';
   if (!get_magic_quotes_gpc()) return $_POST[$nome];
   if (!is_array($_POST[$nome])) return stripslashes($_POST[$nome]);
   $aX = array();
   foreach($_POST[$nome] as $vX) {
   	$aX[] = stripslashes($vX);
   }
   return $aX;
}

function reqDef($nome,$valore) {
	if (!isset($_REQUEST[$nome])) {
		$_REQUEST[$nome] = $valore;
		return true;
	}
	return false;
}

function reqVar($nome) {
   global $_REQUEST;
   if (!isset($_REQUEST[$nome])) return '';
   if (!get_magic_quotes_gpc()) return $_REQUEST[$nome];
   if (!is_array($_REQUEST[$nome])) return stripslashes($_REQUEST[$nome]);
   $aX = array();
   foreach($_REQUEST[$nome] as $kX => $vX) {
   	$aX[$kX] = stripslashes($vX);
   }
   return $aX;
}

function reqVarTrim($nome) {
   return trim(reqVar($nome));
}

function reqVarAS($nome) {
   return addslashes(reqVar($nome));
}

function reqVarHE($nome) {
   return htmlentities(reqVar($nome));
}

function reqVarUE($nome) {
   return urlencode(reqVar($nome));
}

function str2num($str) {
	$str = str_replace(",",".",(str_replace(".","",trim($str))));
	if ($str == "") return "0";
	if (!is_numeric($str)) {
		return false;
	}
	return $str;
}

function num2str($num,$nDec='',$leftZero=0) {
	if ($nDec=='' || $nDec < 0) {
		$nDec = strlen($num-floor($num))-2;
		if ($nDec < 0) $nDec = 0;
	}
	$str = number_format($num,$nDec,",",".");
	if ($leftZero > 0) {
		$str = str_pad($str,"0",$leftZero,STR_PAD_LEFT);
	}
	return $str;
}

function reqVarStr2num($nome) {
	return str2num(reqVar($nome));
}

function str2date($str) {
	$odx = new rglDate();
	if (!$odx->setDMY($str)) {
		return false;
	}
	return $odx->getUnix();
}

function YMD2DMY($strYMD,$sep='/') {
	$odx = new rglDate();
	if (!$odx->setYMD($strYMD)) {
		return "";
	}
	return $odx->getDMY($sep);
}

function DMY2YMD($strDMY,$sep="-", $y=4) {
	$odx = new rglDate();
	if (!$odx->setDMY($strDMY)) {
		return "";
	}
	return $odx->getYMD($sep,$y);
}

function str2dateDMY($str) {
	$sD = str2date($str);
	if ($sD === false) return "";
	return date("d/m/Y",$sD);
}

function reqVarStr2date($nome) {
	return str2date(reqVar($nome));
}

function reqVarStr2YMD($nome) {
	$dx = str2date(reqVar($nome));
	if ($dx === false) {
		return "0000-00-00";
	}
	return date("Y-m-d",$dx);
}

function reqVarStr2DMY($nome) {
	return str2dateDMY(reqVar($nome));
}

function reqVarInt($nome) {
	return intval(reqVar($nome));
}

function YMD2dataHI($strYMD) {
	$odx = new rglDate();
	if (!$odx->setYMD($strYMD)) {
		return "";
	}
	return date("d/m/y H:i",strtotime($strYMD));
}

function rglErr($mess,$error_type=E_USER_ERROR){
	rglLogErr($mess);
	if (!defined('RGL_URL_ROOT')) {
       $pos = strpos($_SERVER['PHP_SELF'],"/app/");
       if ($pos === false) {
          die("Pagina: ".$_SERVER['PHP_SELF']." - Errore: $error_type - $mess.");
       }
       define('RGL_URL_ROOT', substr($_SERVER['PHP_SELF'],0,$pos));
    }    
    if (!isset($_SERVER['HTTP_HOST'])) { // esecuzione batch - linea comando
        echo "*** ERRORE ***\r\n" 
      	."*** pagina : ".urlencode($_SERVER['PHP_SELF'])."\r\n"
      	."*** errore : ".$error_type." - ".$mess."\r\n"
      	."*** TERMINAZIONE ANOMALA ***\r\n";
        exit();
	}	
	if (!defined('XSN')) define("XSN","0.0");
	if (headers_sent()) {		
		echo "<script>window.top.location.href = '".RGL_URL_ROOT."/app/_com/error.php?".
           "pagina_self=".urlencode($_SERVER['PHP_SELF'])."&errno=".$error_type.
		   "&errstr=".urlencode(substr($mess,0,1000)).
           "&errfile=&errline=&xsn=".urlencode(XSN)."';</script>";
      exit();
    }         	
    header("location: ".RGL_URL_ROOT."/app/_com/error.php?".
           "pagina_self=".urlencode($_SERVER['PHP_SELF'])."&errno=".$error_type.
		   "&errstr=".urlencode(substr($mess,0,1000)).
           "&errfile=&errline=&xsn=".urlencode(XSN));
    exit();
    
}

function rglErrSess($mess,$error_type=E_USER_ERROR){
   if (!defined('RGL_URL_ROOT')) {
      $pos = strpos($_SERVER['PHP_SELF'],"/com/");
      if ($pos === false) {
         $pos = strpos($_SERVER['PHP_SELF'],"/mod/");
      }
      if ($pos === false) {
         die("Pagina: ".$_SERVER['PHP_SELF']." - Errore: $error_type - $mess.");
      }
      define('RGL_URL_ROOT', substr($_SERVER['PHP_SELF'],0,$pos));
   }
   if (headers_sent()) {
      echo "<script>window.top.location.href = '".RGL_URL_ROOT."/app/_com/sessError.php?".
         "pagina_self=".urlencode($_SERVER['PHP_SELF'])."&errno=".$error_type.
			"&errstr=".urlencode(substr($mess,0,1000)).
         "&errfile=&errline=';</script>";
      exit();
   }
   header("location: ".RGL_URL_ROOT."/app/_com/sessError.php?".
         "pagina_self=".urlencode($_SERVER['PHP_SELF'])."&errno=".$error_type.
			"&errstr=".urlencode(substr($mess,0,1000)).
         "&errfile=&errline=");
   exit();
}

function rgl_error_handler($errno, $errstr, $errfile, $errline){
	global $objSess;
	if (!defined('E_DEPRECATED')) {
		define('E_DEPRECATED','zxcv');
	}
   switch ($errno) {
   case E_USER_WARNING:
   case E_USER_NOTICE:
   case E_WARNING:
   case E_NOTICE:
   case E_STRICT:
   case E_DEPRECATED:
   	//dbg_($errno." - ".$errstr." - file: $errfile - riga: $errline");
   	if (!is_object($objSess) 
   	|| !isset($objSess->aSV['logWarning'])
   	|| $objSess->aSV['logWarning']) {
      	rglLogWarn($errno." - ".$errstr." - file: $errfile - riga: $errline");
   	}
      return;
   default:
      rglLogErr($errno." - ".$errstr." - file: $errfile - riga: $errline");
		if (defined("RGL_WEB_SERVICE_FLAG")) {
			$sXml = "<rglRisposta>";
			$oXmlEsito = new rglTagXML("rglEsito");
			$oTagX = new rglTagXML("codice");
			$oTagX->setData('590'); 
			$oXmlEsito->addFiglio($oTagX);
			$oTagX = new rglTagXML("descrizione");
			$oTagX->setData($errno." - ".$errstr." - file: $errfile - riga: $errline."); 
			$oXmlEsito->addFiglio($oTagX);
			$sXml .= $oXmlEsito->getXML();
			$sXml .= "</rglRisposta>";
			header("Content-type: application/xml");
			header('Content-length: '.strlen($sXml));
			echo $sXml;
			exit();
		}
      $uself = urlencode($_SERVER['PHP_SELF']);
      $uerrstr = urlencode($errstr);
      $uerrfile = urlencode($errfile);
      // aggiungere in querystring $errno $errstr $errfile $errline
   	if (headers_sent()) {
	      echo '<script>window.top.location.href = "'.RGL_URL_ROOT.'/app/_com/error.php?'.
         'pagina_self='.$uself.'&errno='.$errno.'&errstr='.$uerrstr.
         '&errfile='.$uerrfile.'&errline='.$errline.'&xsn='.urlencode(XSN).'";</script>';
      	exit;
   	}
	   header("location: ".RGL_URL_ROOT."/app/_com/error.php?".
	         "pagina_self=".$uself."&errno=".$errno.
				"&errstr=".$uerrstr.
	         "&errfile=$errfile&errline=$errline&xsn=".urlencode(XSN));
	   exit();
      break;
   }
}
/**
 * funzione usata negli script per disbilitare warning
 */
function rglSetNoWarning($stato = true) {
	global $objSess;
   if (is_object($objSess) ) {
   	$objSess->aSV['logWarning'] = !$stato;
   }
}


function verifEmail($email) {
	//return eregi("^[a-z0-9][_\\.a-z0-9-]+@([a-z0-9][_0-9a-z-]+\\.)+([a-z]{2,4})", $email);
	return preg_match('/^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!\.)){0,61}[a-zA-Z0-9_-]?\.)+[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!$)){0,61}[a-zA-Z0-9_]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/', $email);
}


if (!function_exists('unhtmlentities')) { 
	function unhtmlentities($string) {
		// replace numeric entities
		$string = preg_replace('~&#x([0-9a-f]+);~ei', 'chr(hexdec("\\1"))', $string);
		$string = preg_replace('~&#([0-9]+);~e', 'chr("\\1")', $string);
		// replace literal entities
		$trans_tbl = get_html_translation_table(HTML_ENTITIES);
		$trans_tbl = array_flip($trans_tbl);
		return strtr($string, $trans_tbl);
	}
}

function lpad($str,$lung,$pad) {
	return str_pad($str,$lung,$pad,STR_PAD_LEFT);
}

function rpad($str,$lung,$pad) {
	return str_pad($str,$lung,$pad,STR_PAD_RIGHT);
}

function confrontaDate($data1,$data2) {
		$odx1 = new rglDate();
      if ($odx1->setDMY($data1) === false) { return false; }
      $odx2 = new rglDate();
      if ($odx2->setDMY($data2) === false) { return false; }
      if ($odx1->getYMD() < $odx2->getYMD()) {
         return -1;
      } elseif ($odx1->getYMD() > $odx2->getYMD()) {
         return +1;
      }
      return 0;
}

function eseguiStr($s) {
	global $objDB,$objSess;
	ob_start();
	eval($s);
	$sOut = ob_get_clean();
	if (trim($sOut)!="") {
		rglScriviLog('eval_err', $sOut);
	}
}
